﻿using Ay.Framework.WPF;
using Ay.Framework.WPF.Controls;
using Base.BLL;
using Base.DAL;
using MPSystem;
using MPSystem.Models;
using MPSystem.Util;
using MPSystem.Views.YFQ;
using MPSystem.Views.ZCYL;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Visifire.Charts;

namespace ADX.Views
{
    /// <summary>
    /// ZCYLPage.xaml 的交互逻辑
    /// </summary>
    public partial class ZCYLPage_MG_test : Page
    {
        //通用类
        Common common = new Common();
        public static ZCYLPage_MG_test Me = null;
        public static int cqbh = 0, xdbh = 0;
        public ObservableCollection<ReportMGModel> AllDatas { get; set; } = new ObservableCollection<ReportMGModel>();
        public ObservableCollection<View_MG_Active_ROW> AllWarnDatas { get; set; } = new ObservableCollection<View_MG_Active_ROW>();
        public DataQuery_WYModel SearchModel { get; set; } = new DataQuery_WYModel();
        int lc = 100;//量程
        private double UpperLimit = 40;//上限值
        private double LowLimit = 20;//下限值
        private double WarnLimitMG = 0;
        private double WarnLimitMS = 0;

        private string ComanpyName = "";
        bool FirstReflash = true;
        bool FirstLoadWarn = true;
        List<Dictionary<string, string>> conditons = new List<Dictionary<string, string>>();
        private string bh = "", dtStart = "", dtEnd = "", wz = "", channel = "", minP = "", isMPa = "", zbhs = "", IfVisible = "是";

        private List<string> channel_List = new List<string>();

        private bool _IsBusy = false;
        public bool IsBusy
        {
            get { return _IsBusy; }
            set { _IsBusy = value; }
        }

        public ZCYLPage_MG_test()
        {
            InitializeComponent();
            Loaded += AyPage_Loaded;
            Me = this;
        }


        void AyPage_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= AyPage_Loaded;

            var rcq = ConfigService.GetCQ(true);
            if (rcq.Count() == 0)
            {
                AyMessageBox.ShowError("没有测区！");
                return;
            }
            combcq.ItemsSource = rcq;
            combcq.SelectedIndex = 0;
            //巷道
            var rxd = ConfigService.GetXD(rcq.ElementAt(0).CQBH);
            combxd.ItemsSource = common.LoadCombox_IECobx(rxd);
            if (rxd.Count() > 0) combxd.SelectedIndex = 1;

            ComanpyName = common.GetCompanyName();
            T_CompayName.Text = ComanpyName + "锚 杆 / 索 监 测 报 表";

            UpdateHead();
        }

        #region 更新表头
        private void UpdateHead()
        {
            if (combxd.SelectedItem == null || AyCommon.ToInt(combxd.SelectedValue) <= 0)
            {
                hXD.Text = "—";
                hRZBH.Text = "—";
                hDATE.Text = "—";
                return;
            }
            var cond = MGReport_Condition.Me.Cond;
            hXD.Text = ((AyCheckBoxItemModel)combxd.SelectedItem).ItemText;
            hRZBH.Text = cond["rzbh"];
            hDATE.Text = cond["dtStart"] + "至" + cond["dtEnd"];
        }
        #endregion

        private void LayoutRoot_load(object sender, EventArgs e)
        {
            //syncData();
        }


        void syncData()
        {
            UpdateHead();
            cqbh = AyCommon.ToInt(combcq.SelectedValue);
            xdbh = AyCommon.ToInt(combxd.SelectedValue);
            var cond = MGReport_Condition.Me.Cond;
            if (cond.Count == 0) return;
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (o, ea) =>
            {
                //no direct interaction with the UI is allowed from this method
                AyThread.Instance.RunUI(() =>
                {
                    zbhs = cond["bhs"];
                    dtStart = cond["dtStart"];
                    dtEnd = cond["dtEnd"];
                    lc = AyCommon.ToInt(cond["lc"]);//量程
                    string count = cond["count"];//报警输出，0：全部 1：最后一条
                    string rzbh = cond["rzbh"];
                    bool draw = cond["draw"] == "1";
                    DataMgService ds = new DataMgService();

                    string[] s = zbhs.Split(',');
                    int[] bhs = new int[s.Length];//编号列表
                    for (int b = 0; b < s.Length; b++)
                    {
                        bhs[b] = AyCommon.ToInt(s[b]);
                    }
                    DateTime db = AyCommon.ToDateTime(dtStart), de = AyCommon.ToDateTime(dtEnd);
                    SearchModel.StartTime = db;
                    SearchModel.EndTime = de;
                    //db = new DateTime(2018,12,23); de = new DateTime(2018, 12, 24);
                    var r = ds.Report(cqbh, xdbh, bhs, db, de, count == "1");
                    if (draw)  //确认是否显示曲线
                    {
                        XX.Visibility = System.Windows.Visibility.Visible;
                        XX.Height = 200;
                        CreateChartColumn("监测报表", r);
                    }
                    else
                    {
                        XX.Height = 0;
                        XX.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    LoadTableData(r);

                });
                //CreateChartColumn("测试", strListx, strListy);
            };
            worker.RunWorkerCompleted += (o, ea) =>
            {
                //work has completed. you can now interact with the UI
                busyin1.IsBusy = false;
            };
            //set the IsBusy before you start the thread
            busyin1.IsBusy = true;
            worker.RunWorkerAsync();
        }
        private void btnquery_Click(object sender, RoutedEventArgs e)
        {
            if (combxd.SelectedIndex == -1 || combxd.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和巷道！");
                return;
            }
            xdbh = int.Parse(combxd.SelectedValue.ToObjectString());
            syncData();
        }

        private void btnHquery_Click(object sender, RoutedEventArgs e)
        {
            if (combxd.SelectedIndex == -1 || combxd.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和巷道！");
                return;
            }
            xdbh = int.Parse(combxd.SelectedValue.ToObjectString());
            ShowNavigationWindow("多条件筛选", "/Views/YFQ/MGReport_Condition.xaml", 600, 500);
        }


        private void btnprint_Click(object sender, RoutedEventArgs e)
        {
            //PrintDialog dialog = new PrintDialog();
            //if (dialog.ShowDialog() == true)
            //{
            //    gbox.Visibility = System.Windows.Visibility.Collapsed;
            //    dialog.PrintVisual(printArea, "锚杆/索监测报表");
            //    gbox.Visibility = System.Windows.Visibility.Visible;
            //}
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = "锚杆-索数据报表导出";
            if (saveDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string saveFileName = saveDialog.FileName;
            if (!ExcelHelper.FileEditable(saveFileName))
            {
                AyMessageBox.ShowError("文件被占用，请关闭文件" + saveFileName);
                return;
            }

            var cond = MGReport_Condition.Me.Cond;
            if (cond.Count == 0) return;
            zbhs = cond["bhs"];
            dtStart = cond["dtStart"];
            dtEnd = cond["dtEnd"];
            lc = AyCommon.ToInt(cond["lc"]);//量程
            string count = cond["count"];//报警输出，0：全部 1：最后一条
            string rzbh = cond["rzbh"];
            bool draw = cond["draw"] == "1";
            string[] s = zbhs.Split(',');
            int[] bhs = new int[s.Length];//编号列表
            for (int b = 0; b < s.Length; b++)
            {
                bhs[b] = AyCommon.ToInt(s[b]);
            }
            
            DataMgService.ExportParam param = new DataMgService.ExportParam();
            param.ComanpyName = T_CompayName.Text;
            param.XD = combxd.Text;//巷道名称
            param.RZBH = rzbh;//认证编号
            param.WithChart = draw;//是否生成曲线
            param.WarnLimitMG = WarnLimitMG;//报警值
            param.WarnLimitMS = WarnLimitMS;//报警值
            param.Sign = cond["sign"];

            DataMgService ds = new DataMgService();
            DateTime db = AyCommon.ToDateTime(dtStart);
            DateTime de = AyCommon.ToDateTime(dtEnd);
            //db = new DateTime(2018, 12, 20); de = new DateTime(2018, 12, 30);
            //AyThread.Instance.RunNew(() =>
            //{
            ds.ExportReport(saveFileName, param, cqbh, xdbh, bhs, db, de,count=="1");
            AyMessageBox.ShowInformation("已导出至" + saveFileName);
            //});
        }


        /// <summary>/// 弹出层对象/// </summary>

        public static NavigationWindow window = null;
        /// <summary>/// 使用NavigationWindow弹出页面/// </summary>

        private void ShowNavigationWindow(string title, string uri, int width, int height)
        {
            if (window == null)
            {
                window = new NavigationWindow();
                window.Title = title;
                window.Width = width;
                window.Height = height;
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ResizeMode = ResizeMode.NoResize;
                window.Source = new Uri(uri, UriKind.Relative);
                window.ShowsNavigationUI = false;
                window.Closing += Window_Closing;
                // window.pas += new window.PassValuesHandler(ReceiveValues);
            }
            else
            {
                MGReport_Condition.Me.LoadBH();
            }
            window.ShowDialog();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            MGReport_Condition.Me.UpdateCond();
            window.Hide();
            Me.syncData();
            e.Cancel = true;
        }

        /// <summary>/// 关闭弹出层/// </summary>
        private void CloseNavigationWindow()
        {
            window.Close();
        }

        private void CloseThis(object sender, CancelEventArgs e)
        {
            window = null;
        }
        public void CreateChartColumn(string name, ReportMg rt)
        {
            //创建一个图标
            // Chart chart = new Chart();
            chart.Series.Clear();
            //设置图标的宽度和高度
            //chart.Width = 580;
            //chart.Height = 380;
            //  chart.Margin = new Thickness(100, 5, 10, 5);
            //是否启用打印和保持图片
            if (FirstReflash)
            {
                chart.ToolBarEnabled = false;

                //设置图标的属性
                chart.ScrollingEnabled = false;//是否启用或禁用滚动
                chart.View3D = false;//3D效果显示

                //创建一个标题的对象
                Title title = new Title();

                //设置标题的名称
                title.Text = Name;
                title.Padding = new Thickness(0, 10, 5, 0);
                //向图标添加标题
                chart.Titles.Add(title);
                FirstReflash = false;
            }
            chart.AxesY.Clear();
            Axis yAxis = new Axis();
            //设置图标中Y轴的最小值永远为0           
            yAxis.AxisMinimum = 0;
            yAxis.AxisMaximum = lc;
            //设置图表中Y轴的后缀          
            yAxis.Suffix = "";
            chart.AxesY.Add(yAxis);
            string[] legends = new string[] { "起始应力", "当前应力"};
            for (int i = 0; i < 2; i++)
            {
                //创建第一个DataSeries
                DataSeries oneDataSeries = new DataSeries();
                oneDataSeries.LabelEnabled = true;
                oneDataSeries.LabelText = "#YValue";
                oneDataSeries.LegendText = legends[i];
                oneDataSeries.RenderAs = RenderAs.Column;
                //oneDataSeries.Color = new SolidColorBrush(Colors.LightGreen);
                //创建第一个DataSeries的DataPoint
                DataPoint oneDataPoint = null;
                for (int j = 0; j < rt.CGQBH.Count; j++)
                {
                    oneDataPoint = new DataPoint();
                    oneDataPoint.AxisXLabel = rt.CGQBH[j].ToString();
                    double y = 0;
                    switch (i)
                    {
                        case 0: y = rt.MStart[j]; break;
                        case 1: y = rt.MEnd[j]; break;
                    }
                    oneDataPoint.YValue = y;
                    oneDataSeries.DataPoints.Add(oneDataPoint);
                }
                chart.Series.Add(oneDataSeries);
            }
            if (FirstLoadWarn)
            {
                TrendLine tl = new TrendLine();
                tl.Value = WarnLimitMG;
                tl.LineThickness = 1;
                //tl.LabelText = "上限50MP";
                tl.LineColor = new SolidColorBrush(Colors.LightPink);
                chart.TrendLines.Add(tl);
                FirstLoadWarn = false;

                TrendLine t2 = new TrendLine();
                t2.Value = WarnLimitMS;
                t2.LineThickness = 1;
                //tl.LabelText = "上限50MP";
                t2.LineColor = new SolidColorBrush(Colors.LightGreen);
                chart.TrendLines.Add(t2);
                FirstLoadWarn = false;
            }
        }

        void LoadTableData(ReportMg rt)
        {
            if (rt == null) return;
            AllDatas.Clear();
            for (int i = 0; i < rt.CGQBH.Count; i++)
            {
                ReportMGModel cc = new ReportMGModel();
                cc.MBH = rt.CGQBH[i];
                cc.CGQLX = rt.LX[i] == "MG" ? "锚杆" : "锚索";
                cc.CGQWZ = rt.WZ[i];
                cc.MGZJ = rt.MGZJ[i];
                cc.MDATA = rt.MStart[i];
                cc.END_MDATA = rt.MEnd[i];
                cc.Delta = cc.END_MDATA-cc.MDATA;
                AllDatas.Add(cc);
            }
            if (AllDatas.Count > 0)
            {
                tableView.ItemsSource = AllDatas;
            }

            AllWarnDatas.Clear();
            for (int i = 0; i < rt.Warn.Count && i <= 100; i++)
            {
                ReportMG_WarnROW cc = new ReportMG_WarnROW();
                Db.Cpy(rt.Warn[i], cc);
                cc.WarnLimit = cc.CGQLX=="MG"?WarnLimitMG: WarnLimitMS;
                AllWarnDatas.Add(cc);
            }
            if (AllWarnDatas.Count > 0)
            {
                tableView1.ItemsSource = AllWarnDatas;
            }

        }

        private void combcq_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combcq.SelectedValue == null) return;
            cqbh = AyCommon.ToInt(combcq.SelectedValue);
            var xdSource = ConfigService.GetXD(cqbh);
            combxd.ItemsSource = common.LoadCombox_IECobx(xdSource);
            if (xdSource.Count() > 0) combxd.SelectedIndex = 1;
        }

        private void Combxd_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            xdbh = AyCommon.ToInt(combxd.SelectedValue);
            UpdateHead();
            if (combxd.SelectedValue == null) return;
            View_MG_INI_CS cs = ConfigService.FindMg(cqbh, xdbh);
            if (cs != null)
            {
                WarnLimitMG = cs.MGBJZ;
                WarnLimitMS = cs.MSBJZ;
                FirstLoadWarn = true;
            }
        }
    }
}
